package org.twnmayberry.jpa;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.twnmayberry.bo.Activity;
import org.twnmayberry.bo.POI;
import org.twnmayberry.dao.POIDAO;

public class POIDAOImpl implements POIDAO {

	private static Log log = LogFactory.getLog(POIDAOImpl.class);
	private EntityManager em;
	
	public POIDAOImpl(EntityManager man) {
		em = man;
	}
	
	/**
	 * Couldnt use em.find since it wouldnt return null for no POI so used this instead.
	 */
	@Override
	public POI getPOIByID(long id) {
		POI results = null;
		results = em.find(POI.class, id);
		return results;
	}

	@Override
	public List<POI> getPOIsByFirstMiddleLastName(String firstName,
			String middleName, String lastName) {
		Query query = em.createQuery("Select a from POI as a where firstName = '" + firstName 
				+ "' and middleName = '" + middleName + "' and lastName = '" + lastName + "'");
		List<POI> resultPOIs = new ArrayList<POI>();
		for(Object entry : query.getResultList()) {
			POI results = (POI)entry;
			resultPOIs.add(results);
		}
		return resultPOIs;
	}

	@Override
	public List<POI> getPOIsByAlias(POI alias) {
		Query query = em.createQuery("Select a from POI as a where :alias member of a.aliases");
		query.setParameter("alias", alias);
		List<POI> resultPOIs = new ArrayList<POI>();
		for(Object entry : query.getResultList()) {
			POI results = (POI)entry;
			resultPOIs.add(results);
		}
		return resultPOIs;
	}

	@Override
	public List<POI> getPOIsByActivity(Activity active) {
		Query query = em.createQuery("Select a from POI as a where :activity member of a.activities");
		query.setParameter("activity", active);
		List<POI> resultPOIs = new ArrayList<POI>();
		for(Object entry : query.getResultList()) {
			POI results = (POI)entry;
			resultPOIs.add(results);
		}
		return resultPOIs;
	}

	@Override
	public void createPOI(POI newPOI) {
		
		em.persist(newPOI);
	}

	@Override
	public boolean deletePOI(POI deadPOI) {
		em.remove(deadPOI);
		return true;
	}

	@Override
	public long purgePOIs() {
		int results = 0;
		for(POI person : getAllPOIs()) {
			em.remove(person);
			results++;
		}
		return results;
	}

	@Override
	public void updatePOI(POI tempPOI) {
		em.merge(tempPOI);
	}

	@Override
	public void setEntityManager(EntityManager em) {
		this.em = em;
	}

	@Override
	public List<POI> getAllPOIs() {
		List<POI> createQuery = em.createQuery("select p from POI p", POI.class).getResultList();
		return createQuery;
	}

}
